<?php

namespace Biz\service\advertisement\apiModule;


use Biz\model\advertisement\MHhzPositionStartApp;
use Doraemon\service\Videos\Videos;
use Doraemon\tools\HhzClient;
use Doraemon\tools\ImgUrl;

class AppStart extends BaseModule
{

    const FORMAT_HIT = 'formatDateSeparateHit';
    const CLICK_TEXT = [
        '点击跳转详情页或第三方平台',
        '立即查看',
        '点击查看',
        '点击参与',
        '一键查询',
        '立即匹配',
        '立即讨论',
        '参与话题'
    ];

    public static function getDefaultClickText(): string
    {
        return self::CLICK_TEXT[0];
    }

    public static function getClickText()
    {
        return array_combine(self::CLICK_TEXT, self::CLICK_TEXT);
    }

    public function getExtInfo($info)
    {
        $id = $info['id'] ?? 0;
        $ext = MHhzPositionStartApp::get('*', ['position_base_info_id' => $id]);
        $material_id = $ext['material_id'];
        $material_type = $ext['material_type'];
        $response = [
            'full_screen' => $ext['full_screen'],
            'load_limit' => $ext['load_limit'],
            'video_type' => $ext['video_type'] ?: MHhzPositionStartApp::VEDIO_PLAY,
            'click_white' => $ext['click_white'],
            'click_text' => $ext['click_text'] ?? '',
            'skip' => $ext['skip'],
            'material_type' => $material_type,
            'pic_id' => [$material_id],
            'whole_pic_id' => [$material_id, $ext['pic_1'], $ext['pic_2'], $ext['pic_3'], $ext['pic_4']],
        ];

        if (in_array($material_type, [MHhzPositionStartApp::MATERIAL_TYPE_PIC, MHhzPositionStartApp::MATERIAL_TYPE_AD])) {
            $response['material_type_ad'] = [
                1 => $material_type,
                2 => $material_type,
            ];
            $response['material_type'] = (empty($ext['pic_1']) && empty($ext['pic_2']) && empty($ext['pic_3']) && empty($ext['pic_4'])) ? 1 : 2;
        } elseif ($material_type == MHhzPositionStartApp::MATERIAL_TYPE_VEDIO) {
            $response['video'] = $material_id;
        }

        return $response;
    }

    public function extListMap($ids)
    {
        $response = [];

        $ext = empty($ids) ? [] : MHhzPositionStartApp::select('*', ['position_base_info_id' => $ids]);
        $extMap = empty($ext) ? [] : array_column($ext, null, 'position_base_info_id');
        $videoId = empty($ext) ? [] : array_column($ext, 'material_id');
        $video = empty($videoId) ? [] : Videos::getCommunityBackgroundVideosByIds($videoId);

        foreach ($extMap as $id => $v) {
            $material_id = $v['material_id'];
            $material_type = $v['material_type'];
            $video_type = $v['video_type'] ?? '';
            $v['url'] = $material_type == MHhzPositionStartApp::MATERIAL_TYPE_VEDIO ? $video[$material_id][$video_type] : ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $material_id, ImgUrl::IMAGE_SIZE_OP_ORI);
            $response[$id] = $v;
        }

        return $response;
    }

    public function formatAdmListExtInfo(&$v, $map)
    {
        $ext = $map[$v['id']] ?? [];

        $material_id = '';
        if (in_array($ext['material_type'], [MHhzPositionStartApp::MATERIAL_TYPE_PIC, MHhzPositionStartApp::MATERIAL_TYPE_AD])) {
            $material_id = empty($ext['material_id']) ? '' : ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $ext['material_id'], ImgUrl::IMAGE_SIZE_OP_ORI);
            $extImg = [$material_id];
            if ($ext['pic_1'])  $extImg[] = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $ext['pic_1'], ImgUrl::IMAGE_SIZE_OP_ORI);
            if ($ext['pic_2'])  $extImg[] = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $ext['pic_2'], ImgUrl::IMAGE_SIZE_OP_ORI);
            if ($ext['pic_3'])  $extImg[] = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $ext['pic_3'], ImgUrl::IMAGE_SIZE_OP_ORI);
            if ($ext['pic_4'])  $extImg[] = ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $ext['pic_4'], ImgUrl::IMAGE_SIZE_OP_ORI);
            $material_id = $extImg;
        } elseif ($ext['material_type'] == MHhzPositionStartApp::MATERIAL_TYPE_VEDIO) {
            $video = Videos::getCommunityBackgroundVideosByIds($ext['material_id']);
            $video = empty($video) ? [] : $video[$ext['material_id']];
            $material_id = $video['play_url'] ?? '';
        }
        $v['skip'] = $ext['skip'];
        $v['material_id'] = $material_id;
        $v['material_type_desc'] = MHhzPositionStartApp::MATERIAL_TYPE_MAP[$ext['material_type']] ?? '';
        $v['material_type'] = $ext['material_type'];
        $v['load_limit'] = $ext['load_limit'] === '' ? '默认3秒' : $ext['load_limit'] . 'ms';
    }

    public function format($hit, $uid, $userProfileExt, $statSignExt)
    {
        //使用客户端的屏幕宽高
        if ($userProfileExt) {
            $width = $userProfileExt['screen_width'] ?? 0;
            $height = $userProfileExt['screen_height'] ?? 0;
            $rate = $height > 0 ? $width / $height: 0;
        } else {
            $did = HhzClient::getDid();
            $width_height = \Doraemon\cache\PositionModule\DidScreen::get(\Doraemon\cache\PositionModule\DidScreen::_CACHE_KEY_PREFIX_ . $did);
            $arr = $width_height ? explode(':', $width_height) : [];
            $width = $arr[0] ?? 0;
            $height = $arr[1] ?? 0;
            $rate = $height > 0 ? $width / $height: 0;
        }

        $ext = empty($hit) ? [] : array_column($hit, 'ext');
        $extMap = empty($ext) ? [] : array_column($ext, null, 'position_base_info_id');
        $videoId = empty($ext) ? [] : array_column($ext, 'material_id');
        $video = empty($videoId) ? [] : Videos::getCommunityBackgroundVideosByIds($videoId);

        $response = [];
        foreach ($hit as $k => $v) {
            $temp = null;
            if ($v) {
                $id = $v['id'] ?? 0;
                $ext = $extMap[$id] ?? [];
                $pic_1 = $ext['pic_1'] ?? '';
                $pic_2 = $ext['pic_2'] ?? '';
                $pic_3 = $ext['pic_3'] ?? '';
                $pic_4 = $ext['pic_4'] ?? '';
                $material_id = $ext['material_id'];
                if ($rate >= 0.1 && $rate < 0.49) {
                    $material_id = $pic_1;
                }

                if ($rate >= 0.56 && $rate < 1) {
                    $material_id = $pic_2 ?: $pic_4;
                }

                if ($rate >= 0.5 && $rate < 0.55) {
                    $material_id = $pic_3;
                }
                $material_id = $material_id ?: $ext['material_id'];

                $material_type = $ext['material_type'];
                $video_type = $ext['video_type'] ?? '';
                $full_screen = $ext['full_screen'] ?? MHhzPositionStartApp::FULL_SCREEN_NORMAL;
                $url = $material_type == MHhzPositionStartApp::MATERIAL_TYPE_VEDIO ? $video[$material_id][$video_type] : ImgUrl::getUrl(ImgUrl::APPTYPE_OP, $material_id, ImgUrl::IMAGE_SIZE_OP_ORI);
                $click_text = $ext['click_text'] ?? '';

                $linkParams = $v['link_params'];
                $statSign = $this->statSign($v, $statSignExt);
                $linkParams = self::addStatSignToLink($linkParams, $statSign);
                $link = $this->generateLink($v['link_type'], $linkParams);

                $temp = [
                    'id' => $id,
                    'type' => $material_type,
                    'start_time' => strtotime($v['start_show_time']),
                    'end_time' => strtotime($v['end_show_time']),
                    'edittime' => strtotime($v['edittime']),
                    'max_load_time' => empty($ext['load_limit']) ? 3000 : intval($ext['load_limit']),
                    'link' => $link,
                    'full_screen' => $full_screen,
                    'url' => $url,
                    'skip' => $material_type == MHhzPositionStartApp::MATERIAL_TYPE_PIC ? ($ext['skip'] ?? '1') : '1',
                    'click_white' => (int)$ext['click_white'],
                    'click_text' => $click_text ?: self::CLICK_TEXT[0],
                    'statSign' => $statSign,
                ];
            }
            $response[$k] = $temp;
        }

        return $response;
    }

    public function uniquePos($v): string
    {
        $nowDate = date('Y-m-d H:i:s');
        return $v['start_show_time'] > $nowDate;
    }

}